using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraAction : MonoBehaviour
{
    public float shakeLevel = 3f; // 震动幅度
    public float setShakeTime = 0.5f; // 震动时间
    public float shakeFps = 45f; // 震动的FPS

    public bool isshakeCamera = false; // 震动标志

    public bool isRedshake = false; // 震动标志
    private float fps;
    private float shakeTime = 0.0f;
    private float frameTime = 0.0f;
    private float shakeDelta = 0.005f;
    private Camera selfCamera;
    public GameObject redPanel;
    public float setRedShakeTime;
    public float RedShakeTime;
    public Transform[] followedObjectTranform;
    private int PlayerID;

    void Start()
    {
        isshakeCamera = false;
        selfCamera = gameObject.GetComponent<Camera>();
        shakeTime = setShakeTime;
        fps = shakeFps;
        frameTime = 0.03f;
        shakeDelta = 0.005f;
        
    }

    // Update is called once per frame
    void Update()
    {
        Shake_Camera();
        ShakeRed();
        fllowedObject();
    }

    void ShakeRed()
    {
        if (isRedshake)
        {
            RedShakeTime+=Time.deltaTime;
            redPanel.SetActive(true);
            if (RedShakeTime>=setRedShakeTime)
            {
                RedShakeTime=0;
                redPanel.SetActive(false);
                isRedshake=false;
            }

        }
    }

    void fllowedObject()
    {
        PlayerID=GameObject.Find("UdpServer").GetComponent<WebSocketDemo>().PlayerId;
        if(PlayerID==-1)
            return;
        transform.position = new Vector3(followedObjectTranform[PlayerID].position.x, followedObjectTranform[PlayerID].position.y, -10f);
    }

    void Shake_Camera()
    {
        if (isshakeCamera)
        {
            if (shakeTime > 0)
            {
                shakeTime -= Time.deltaTime;
                if (shakeTime <= 0)
                {
                    shakeTime = setShakeTime;
                    selfCamera.rect = new Rect(0.0f, 0.0f, 1.0f, 1.0f);
                    isshakeCamera = false;
                }
                else
                {
                    frameTime += Time.deltaTime;

                    if (frameTime > 1.0 / fps)
                    {
                        frameTime = 0;
                        float xShake = shakeDelta * (-1.0f + shakeLevel * Random.value);
                        float yShake = shakeDelta * (-1.0f + shakeLevel * Random.value);
                        selfCamera.rect = new Rect(xShake, yShake, 1.0f, 1.0f);
                    }
                }
            }
        }
    }
}
